#include "GeoNeighbours.h"

using namespace H3D;

// Add this node to the H3DNodeDatabase system.
H3DNodeDatabase GeoNeighbours::database( 
                                 "GeoNeighbours", 
                                 &(newInstance<GeoNeighbours>), 
                                 typeid( GeoNeighbours ),
                                 &GeoH3DNeighboursNode::database );

namespace GeoNeighboursInternals {
  FIELDDB_ELEMENT( GeoNeighbours, vector, INPUT_OUTPUT );
}

// Constructor
GeoNeighbours::GeoNeighbours( 
               Inst< SFNode >  _metadata,
               Inst< MFInt32 >  _vector ) :
  GeoH3DNeighboursNode( _metadata ),
  vector  ( _vector   ) {

  type_name = "GeoNeighbours";
  database.initFields( this );

  vector->route( propertyChanged );
}

// Accessors
vector< unsigned long > GeoNeighbours::getNeighbours( unsigned int index ) {
	std::vector< int > GeoNeighbours( vector->getValue() );
	std::vector< unsigned int > GeoNeighboursIndexes( getNeighboursIndexes() );

	return std::vector<unsigned long> (GeoNeighbours.begin() + GeoNeighboursIndexes[ index ] + 1,
		GeoNeighbours.begin() + GeoNeighboursIndexes[ index+1 ] );
}

const vector< unsigned long > GeoNeighbours::getNeighbours( unsigned int index ) const{
	std::vector< int > GeoNeighbours( vector->getValue() );
	std::vector< unsigned int > GeoNeighboursIndexes( getNeighboursIndexes() );

	return std::vector<unsigned long> (GeoNeighbours.begin() + GeoNeighboursIndexes[ index ] + 1,
		GeoNeighbours.begin() + GeoNeighboursIndexes[ index+1 ] );
}

vector< unsigned int > GeoNeighbours::getNeighboursIndexes () const{
	std::vector< int > GeoNeighbours( vector->getValue() );
	std::vector< int >::iterator prc( GeoNeighbours.begin() ),
							fin( GeoNeighbours.end() );
	std::vector< unsigned int > res;
	unsigned int count( 0 );
	res.push_back( count );

	while( prc!=fin )
	{	if ( *prc == -1 )
			res.push_back( count );
		count++;
		prc++;
	}
/*	useless normally
	if ( *(fin-1) == -1 )
		res.pop_back();
*/
	return res;
}
